#include "backoff_spinlock.h"
#include "../atomic/cpu_pause.h"
#include <time.h>

#define MIN_BACKOFF 1
#define MAX_BACKOFF 1000

void backoff_spinlock_init(backoff_spinlock_t *lock) {
    atomic_store(&lock->locked, 0, RELAXED);
}

static inline void backoff(int *backoff_time) {
    for (int i = 0; i < *backoff_time; i++) {
        cpu_pause();
    }
    // 指数增长退避时间，但不超过最大值
    *backoff_time = (*backoff_time * 2 < MAX_BACKOFF) ? 
                     *backoff_time * 2 : MAX_BACKOFF;
}

void backoff_spinlock_lock(backoff_spinlock_t *lock) {
    int backoff_time = MIN_BACKOFF;
    
    for (;;) {
        while (atomic_load(&lock->locked, RELAXED)) {
            backoff(&backoff_time);
        }
        
        if (!atomic_exchange(&lock->locked, 1, ACQ_REL)) {
            return;
        }
        
        // 如果获取锁失败，增加退避时间
        backoff_time = MIN_BACKOFF;
    }
}

void backoff_spinlock_unlock(backoff_spinlock_t *lock) {
    atomic_store(&lock->locked, 0, RELEASE);
} 